#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>

static int max_cache_len = 1<<10;

typedef struct{
	uint64_t	ip;		//写入ip
	uint32_t   	port;		//写入端口
	time_t		expiretime;	//到期时间
	char		key[256];	//写入key
}qdata_t;

int get_time_filename(time_t t, char* filename);

int main(int argc, char** argv){

	int count = 10;
	if(argc > 1){
		count = atoi(argv[1]);
	}
	
	printf("mct service start\r\n");
	// alloc buf
	char* buf = new char[sizeof(qdata_t) * max_cache_len];
	char filename[1024];
	int index =0;
	
	time_t tm;
	time(&tm);
	get_time_filename(tm, filename);
	
	FILE *fp;
	if((fp = fopen(filename, "wb+")) == NULL){
		printf("filename:%s open faile\r\n",filename);
		return 1;
	}

//	printf("%d", sizeof(qdata_t));
//	return 1;	

	memset(buf, 0, sizeof(qdata_t) * max_cache_len);
	qdata_t m_data;
	char* begin = buf;
	while(++index <= count){
		m_data.ip 		= 123123;
		m_data.port 		= 6800;
		memset(m_data.key, 0, sizeof(m_data.key));
		memcpy(m_data.key, "test", 4);
		m_data.expiretime 	= time(NULL);
		memcpy(begin, &m_data, sizeof(qdata_t));
		begin += sizeof(qdata_t); 
		printf("size:%d\r\n", sizeof(m_data.key));
		//printf("mydata:ip:%d,port:%d,key:%s,expiretime:%d\r\n",m_data.ip,m_data.port,m_data.key,m_data.expiretime);
		//printf("mydata:ip:%d,port:%d,key:,expiretime:%d\r\n", m_data.ip, m_data.port, m_data.expiretime);

		if(begin - buf >= sizeof(qdata_t) * max_cache_len){
			printf("save buf\r\n");
			fwrite(buf, begin - buf, 1, fp);
			memset(buf, 0, sizeof(qdata_t) * max_cache_len);
			begin = buf;
		}
	}

	 if(begin - buf >= 0){
        	fwrite(buf, begin - buf, 1, fp);
		printf("last save buf\r\n");
          }

	fclose(fp);

	// 释放
	if (buf) delete buf;

	printf("mct service stop\r\n");
	return 1;
}

//根据时间获取路径名
int get_time_filename(time_t t, char* filename){
	struct tm *p = gmtime(&t);
	return sprintf(filename, "./d_%02d_%02d_%02d_%02d.dat", 1990 + p->tm_year, 1 + p->tm_mon, p->tm_mday, 8 + p->tm_hour);
}


